package com.gwt.tirso.gymkhana.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwt.tirso.gymkhana.shared.DelistedException;
import com.gwt.tirso.gymkhana.shared.FieldVerifier;
import com.gwt.tirso.gymkhana.shared.IdGenerator;


public class CreationStep1 implements EntryPoint {

	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel horPanelNTeams = new HorizontalPanel();
	private HorizontalPanel horPanelNQuestions = new HorizontalPanel();
	private HorizontalPanel namePanel = new HorizontalPanel();
	private HorizontalPanel horPanelButtons = new HorizontalPanel();
	private TextBox name = new TextBox();
	private TextArea description = new TextArea();
	private TextArea basicRules = new TextArea();
	private Button acceptButton = new Button();
	private Button cancelButton = new Button();
	private Label nameLabel = new Label();
	private Label descriptionLabel = new Label();
	private Label rulesLabel = new Label();
	private Label nTeamsLabel = new Label();
	private Label nQuestionsLabel = new Label();
	private Label noteLabel = new Label();
	private Label errorLabel = new Label();
	private Label errorNameLabel = new Label("");
	private ListBox listBoxNTeams = new ListBox();
	private ListBox listBoxNQuestions = new ListBox();
	private Gymkhana gymkhana = new Gymkhana();
	private Person p = new Person();
	private boolean valid = true;
	
	private IGymkhanaServiceAsync gymkCon;
	private ILoginServiceAsync loginCon;

	@Override
	public void onModuleLoad() {
		
		loadCreationStep1();
		
	}

	
	private void loadCreationStep1() {
		// buttons: labeling
		acceptButton.setText("Aceptar");
		cancelButton.setText("Cancelar");
		

		// listBoxes
		// number of teams and questions
		for(int i = 1;i < 21; i++){
			listBoxNTeams.addItem(Integer.toString(i));
			listBoxNQuestions.addItem(Integer.toString(i));
		}
		
       

		// nTeamsPanel: adding elements
		horPanelNTeams.add(nTeamsLabel);
		horPanelNTeams.add(listBoxNTeams);

		// nQuestionsPanel: adding elements
		horPanelNQuestions.add(nQuestionsLabel);
		horPanelNQuestions.add(listBoxNQuestions);
		
		// namePanel: adding elements
		namePanel.add(name);
		namePanel.add(errorNameLabel);

		// buttonsPanel: adding elements
		horPanelButtons.add(acceptButton);
		horPanelButtons.add(cancelButton);

		// labels
		nameLabel.setText("Nombre");
		descriptionLabel.setText("Descripcion");
		rulesLabel.setText("Reglas");
		nTeamsLabel.setText("Nº de equipos");
		nQuestionsLabel.setText("Nº de preguntas");
		noteLabel
				.setText("*Nota: El numero de equipos debe de ser mayor al numero de preguntas");

		// text boxes: calculating areas
		name.setMaxLength(25);
		name.setVisibleLength(25);
		description.setVisibleLines(4);
		basicRules.setVisibleLines(4);

		// mainPanel: adding elements
		mainPanel.add(nameLabel);
		mainPanel.add(namePanel);
		mainPanel.add(descriptionLabel);
		mainPanel.add(description);
		mainPanel.add(rulesLabel);
		mainPanel.add(basicRules);
		mainPanel.add(horPanelNTeams);
		mainPanel.add(horPanelNQuestions);
		mainPanel.add(horPanelButtons);
		mainPanel.add(noteLabel);
		
		//Initialize login connection
		loginCon = ConnectionRpc.initRpcLogin();

		errorLabel.addStyleName("errorLabel");
		mainPanel.addStyleName("creationNext");
		RootPanel.get("creation").add(mainPanel);

		// Move cursor focus to name box.
		name.setFocus(true);
		
		
		
		name.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				
				String s =  name.getText();
				
				gymkCon = ConnectionRpc.initRpcGymkhana();
				
				AsyncCallback<String> callback = new AsyncCallback<String>() {

					@Override
					public void onFailure(Throwable caught) {
						errorLabel.setText("Fallo al conectar");
						
					}

					@Override
					public void onSuccess(String result) {
						
						if(result != null){
							errorNameLabel.setText(" El nombre " + result + " no está disponible");
							errorNameLabel.setStyleName("errorLabel");
							valid = false;
							
						}else{
							errorNameLabel.setText(" Nombre disponible");
							errorNameLabel.setStyleName("successLabel");
							valid = true;
						}
						
					}
				};
		
				gymkCon.checkName(s, callback);
				
			}
		});

		// Listen for mouse events on the acceptButton.
		acceptButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				
				loginCon.loginFromSessionServer(new AsyncCallback<Person>() {
					
					@Override
					public void onSuccess(Person result) {
						if(result == null){
							Window.alert("Para acceder a la aplicación debe iniciar sesión");
							cancelStep();
						}else{
							//first, we extract the author and input it in gymkhana
							p = result;
							gymkhana = receiveInfo();
							if (gymkhana == null) {
								mainPanel.add(errorLabel);
							} else {
								step2();
							}
						}
						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						
						String details = caught.getMessage();
				        if (caught instanceof DelistedException) {
				          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
				        }

				        errorLabel.setText("Error: " + details);
				        errorLabel.setVisible(true);

						
					}
				});	
			}
		});

		// Listen for mouse events on the cancelButton.
		cancelButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				cancelStep();
			}
		});
		

		
	}


	public Gymkhana receiveInfo() {

		// sending dates to other window and check all of them
		String nameToList = name.getText();
		if (!FieldVerifier.isValidName(nameToList)||valid == false) {
			errorLabel.setText("Escriba un nombre para la Gymkhana");
			return null;
		}
		String descToList = description.getText();
		if (!FieldVerifier.isValidName(descToList)) {
			errorLabel.setText("Escriba una breve descripcion de la Gymkhana");
			return null;
		}
		String rulesToList = basicRules.getText();
		if (!FieldVerifier.isValidName(nameToList)) {
			errorLabel.setText("Escriba las reglas de la Gymkhana");
			return null;
		}

		int nTeams = listBoxNTeams.getSelectedIndex() + 1;
		int nQuest = listBoxNQuestions.getSelectedIndex() + 1;
		
		int nPoints = 10 * nQuest;

		// Gymkhana object which we sending to another step
		Gymkhana gymk = new Gymkhana();

		gymk.setName(nameToList);
		gymk.setDescription(descToList);
		gymk.setRules(rulesToList);
		gymk.setnMaxTeams(nTeams);
		gymk.setnQuestions(nQuest);
		gymk.setnPoints(nPoints);
		
		

		//gymkhana id, with idgenerator
		String key = IdGenerator.getInstance().getKey();
		gymk.setId(key);

		return gymk;

	}

	private void step2() {
		CreationStep2 p2 = new CreationStep2();
		p2.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);

		// gymkhana´s info
		p2.setGymk(gymkhana);
		p2.setAuthor(p);
	}

	private void cancelStep() {
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("creation").remove(mainPanel);
	}

}
